using System;
using Microsoft.Win32;
using System.Text.RegularExpressions;

namespace CheckRegistryKey
{
    class Program
    {
        static void Main(string[] args)
        {
            if (args.Length != 2 || (args[0].StartsWith("/key=") == false && args[0].StartsWith("/root=") == false))
            {
                Program.ShowSyntax();
                Environment.Exit(-1);
            }

            string keyName = string.Empty;
            string root = string.Empty;

            Regex regex = new Regex(@"/\w+=");
            foreach (string arg in args)
            {
                string param = arg.ToLowerInvariant();
                Match match = regex.Match(param);
                if (match.Success == false)
                {
                    Program.ShowSyntax();
                    Environment.Exit(-1);
                }

                switch (match.Value)
                {
                    case "/key=":
                        keyName = param.Trim(match.Value.ToCharArray());
                        break;

                    case "/root=":
                        root = param.Trim(match.Value.ToCharArray());
                        break;

                    default:
                        Program.ShowSyntax();
                        Environment.Exit(-1);
                        break;
                }
            }

            RegistryKey key = null;
            switch (root)
            {
                case "hklm":
                    key = Registry.LocalMachine.OpenSubKey(keyName);
                    break;

                case "hkcu":
                    key = Registry.CurrentUser.OpenSubKey(keyName);
                    break;
            }
            
            if (key == null)
            {
                Console.WriteLine("Key could not be found");
                Environment.Exit(1);
            }
            else
            {
                Console.WriteLine("Key was present in the registry");
                Environment.Exit(0);
            }
        }

        private static void ShowSyntax()
        {
            Console.WriteLine("CheckRegistryKey syntax:");
            Console.WriteLine("    CheckRegistryKey /root=[HKCU | HKLM] /key=KEYNAME");
            Console.WriteLine();
        }
    }
}
